/**
 * @description 行政区域页面
 * @author 李艳
 */
import React, {Component} from "react";
import {deleteNode, getAllTree, move, save} from "./RegionService";
import {Button, Col, Form, Input, InputNumber, message, Modal, Row} from "antd";
import {hide, show} from "../../../configs/SharedReducer";
import connect from "react-redux/es/connect/connect";
import EditRegionModal from "./EditRegionModal";
import HeadBreadcrumb from "../../../commons/components/breadcrumb/HeadBreadcrumb";
import {rowGutter} from "../../../configs/DefaultConfig";
import DetailCard from "../../../commons/components/DetailCard";
import StandardTree from "../../../commons/components/StandardTree";
import PageOperateHoc from "../../../commons/components/PageOperateHoc";
import CheckAuth from "../../../commons/components/CheckAuth";
import {checkInputCode} from "../../../commons/utils/CommonUtils";

const FormItem = Form.Item;
const Search = Input.Search;
const confirm = Modal.confirm;

class RegionView extends Component {
  constructor(props) {
    super(props);
    this.initPath = [{name: "行政领域"}]
    this.state = {
      treeData: [],
      searchValue: "",
      tableData: [],
      findResultData: [],
      treeSelectedKeys: [],
      selectedNode: {},
      modalVisible: false,
      confirmLoading: false,
      scrollY: null,
      isAddRoot: false,
    }
  }

  componentWillMount() {
    this.getTreeData();
  }

  onModalRef = (ref) => {
    this.modalRef = ref;
  };

  //网络请求树控件数据（组织机构）
  getTreeData = (param) => {
    this.props.show();
    getAllTree(param).then((result) => {
      if (result) {
        this.setState({treeData: result});
      }
    }).catch(err => {
    }).finally(() => {
      this.props.hide();
    });
  };

  //树节点选择触发
  onTreeSelect = (selectedKeys, selectedNodes) => {
    let data = selectedNodes[0];
    this.setState({treeSelectedKeys: selectedKeys, selectedNode: data});
    this.props.form.setFieldsValue({
      name: data.name, code: data.code, rank: data.rank, shortName: data.shortName,
      pinYin: data.pinYin, parentId: data.parentId, countryId: data.countryId, id: data.id
    })
  };

  judgeTreeSelected = () => {
    if (this.state.treeSelectedKeys.length > 0) {
      return true;
    }
    message.error("请选择一个节点");
    return false;
  };

  //创建根节点
  onAddRootNodeClick = () => {
    this.setState({isAddRoot: true, modalVisible: true})
  };

  //增加节点
  onAddNodeClick = () => {
    if (!this.judgeTreeSelected()) return;

    this.setState({isAddRoot: false, modalVisible: true})
  };

  //删除节点
  onDeleteNodeClick = () => {
    if (!this.judgeTreeSelected()) return;
    let param = this.state.treeSelectedKeys[0];
    let thiz = this;
    confirm({
      title: "温馨提示",
      content: "删除后不可恢复，是否确定删除？",
      onOk() {
        deleteNode(param).then((result) => {
          if (result.status === "SUCCESS") {
            message.success(result.message ? result.message : "删除成功");
            //请求treeData数据刷新本地数据
            thiz.getTreeData();
            thiz.props.form.resetFields()
            thiz.setState({selectedNode:{}})
          } else {
            message.error(result.message ? result.message : "删除失败");
          }
        }).catch((err) => {
        }).finally(() => {
        })
      },
      onCancel() {
      },
    });
  };

  handleEdit = () => {
    //表单数据同步
    if (this.modalRef && this.modalRef.props.form) {
      this.modalRef.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          this.setState({confirmLoading: true});
          save(values).then((result) => {
            if (result.status === "SUCCESS") {
              message.success(result.message ? result.message : "保存成功");
              //请求treeData数据刷新本地数据
              this.getTreeData();
              this.setState({confirmLoading: false, modalVisible: false});
            } else {
              message.error(result.message ? result.message : "保存失败")
              this.setState({confirmLoading: false});
            }
          }).catch(err => {
            this.setState({confirmLoading: false});
          })
        }
      })
    }
  };

  saveEdit = () => {
    //表单数据同步
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        this.props.show()
        save(values).then((result) => {
          if (result.status === "SUCCESS") {
            message.success(result.message ? result.message : "保存成功");
            //请求treeData数据刷新本地数据
            this.getTreeData();
          } else {
            message.error(result.message ? result.message : "保存失败")
          }
        }).catch(err => {
        }).finally(() => {
          this.props.hide()//modal的进度条
        });
      }
    });
  };
  handleModalCancel = () => {
    this.setState({modalVisible: false})
  };

  render() {
    const {getFieldDecorator} = this.props.form;
    const formItemLayout = {
      labelCol: {
        span: 3
      },
      wrapperCol: {
        span: 8
      },
    };

    const buttons = () => {
      return [
        <CheckAuth operateCode="BASIC-XZQYGL-XZQY-ADDROOT" key='addRoot'>
          <Button key={'primary'} className={"primaryButton"} type={"primary"}
                  onClick={this.onAddRootNodeClick}>新增根节点</Button>
        </CheckAuth>,
        <Button.Group key={"elseButton"}>
          <CheckAuth operateCode="BASIC-XZQYGL-XZQY-ADD" key='add'>
            <Button onClick={this.onAddNodeClick}>新增节点</Button>
          </CheckAuth>
          <CheckAuth operateCode="BASIC-XZQYGL-XZQY-DELETE" key='delete'>
            <Button onClick={this.onDeleteNodeClick}>删除</Button>
          </CheckAuth>
        </Button.Group>
      ]
    };
    //表头搜索框
    const search = () => {
      return [
        <Search
          key="search"
          placeholder="输入名称查询"
          onSearch={e => this.handleSearch(e)}
          style={{width: '220px'}}
          allowClear
        />
      ]
    };
    let defaultValue = this.state.selectedNode;
    return (
      <HeadBreadcrumb
        // pathData={this.initPath}
        className={"allocation-page"}
        style={{overflow: "hidden"}}
      >
        <Row gutter={rowGutter} style={{height: "100%"}}>
          {/*左边的树状控件*/}
          <Col span={12} style={{height: "100%"}}>
            <DetailCard
              title="行政区域"
              style={{height: "100%"}}
              bodyStyle={{height: "calc(100% - 53px)"}}
            >
              <StandardTree
                leftExtra={buttons()}
                onSelect={this.onTreeSelect}
                dadaSource={this.state.treeData}
                moveService={move}
                initService={this.getTreeData}/>
              {this.state.modalVisible && <EditRegionModal
                modalVisible={this.state.modalVisible}
                confirmLoading={this.state.confirmLoading}
                handleOk={this.handleEdit}
                handleCancel={this.handleModalCancel}
                onRef={this.onModalRef}
                isAddRoot={this.state.isAddRoot}
                defaultValue={this.state.selectedNode}
              />}
            </DetailCard>
          </Col>

          {/*右边的控件*/}

          <Col span={12} style={{height: "100%"}}>
            <DetailCard className={"child-card"}
                        title={this.state.selectedNode.name ? this.state.selectedNode.name : "详细信息"}
                        style={{height: "100%"}}
            >
              <Form className="card-body-content" style={{height: "100%"}}>
                <FormItem
                  {...formItemLayout}
                  style={{display: 'none'}}
                  label="id">
                  {getFieldDecorator('id', {})(
                    <Input/>
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  style={{display: 'none'}}
                  label="countryId">
                  {getFieldDecorator('countryId', {})(
                    <Input/>
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="代码">
                  {getFieldDecorator('code', {
                    rules: [{required: true, message: '请填写代码!'},{max:10,message:"不超过10个字符"},checkInputCode()]
                  })(
                    <Input disabled={!defaultValue.parentId}/>
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="名称">
                  {getFieldDecorator('name', {
                    rules: [{required: true, message: '请填写名称!'},{max:50,message:"不超过50个字符"}]
                  })(
                    <Input/>
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="排序">
                  {getFieldDecorator('rank', {
                    rules: [{required: true, message: '请填写排序!'}]
                  })(
                    <InputNumber maxLength={9} precision={0} min={0}  style={{width: "100%"}}/>
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="缩写">
                  {getFieldDecorator('shortName', {})(
                    <Input/>
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="拼音">
                  {getFieldDecorator('pinYin', {})(
                    <Input/>
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  style={{display: 'none'}}
                  label="parentId">
                  {getFieldDecorator('parentId', {})(
                    <Input/>
                  )}
                </FormItem>
                <br/>
                <Row>
                  <Col span={3}> </Col>
                  <Col span={8}>
                    <CheckAuth operateCode="BASIC-XZQYGL-XZQY-SAVE" key='addRoot'>
                      <Button type={"primary"} onClick={this.saveEdit}>保存</Button>
                    </CheckAuth>
                  </Col>
                </Row>
              </Form>
            </DetailCard>
          </Col>
        </Row>
      </HeadBreadcrumb>

    )
  }
}

const mapStateToProps = (state) => {
  return {};
};

const mapDispatchToProps = (dispatch) => {
  return {
    show: () => {
      dispatch(show())
    },
    hide: () => {
      dispatch(hide())
    },
  }
};
RegionView = Form.create()(RegionView);
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(PageOperateHoc(RegionView))

